// pages/equip_detail/equip_detail.js
const httprequest = require('../../utils/http_utils.js')
const dateutil = require('../../utils/date_util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    RowGuid: "",
    EquipmentCode: '',
    EquipmentName: '',
    currentTab: 0,
    navScrollLeft: 0,
    navData: [{
        text: '设备信息'
      },
      {
        text: '静态属性'
      },
      {
        text: '设备附件'
      },
      {
        text: '巡检记录'
      },
      {
        text: '维保记录'
      }
    ],
    isshoworder: false, //默认跳转到上一页
    title: '设备详情',
    windowWidth: 0,
    windowHeight: 0,
    equipDatailData: [], //设备信息
    jtsx_list: [], //静态属性
    fssbCount: 0, //附属设备数量
    showzanwu: false,
    havefssb: true, //是否有附属设备
    info: '', //提示信息
    fileList: [], //附件集合
    UploadUrl: httprequest.uploadUrl,
    dialogShow: false,
    videourl: '',
    platform: '', //android or ios
    RecordList: [], //巡检记录集合
    CustomBar:0, //导航栏高度
    maintenancePlanList: [], //维保信息集合
  },

  //跳转巡检详情
  JumpDetails: function(data) {
    console.log(JSON.stringify(data.currentTarget.dataset) + "------------传参")
    wx.navigateTo({
      url: '../xunJianDetails/xunJianDetails?TaskType=2' + '&RowGuid=' + data.currentTarget.dataset.rowguid + '&RoomName=' + data.currentTarget.dataset.roomname + '&IsAlarm=' + data.currentTarget.dataset.isalarm + '&TaskRemark=' + data.currentTarget.dataset.taskremark,
    })
  },

  //跳转维保详情
  MaintenanceDetails: function (e) {
    console.log(JSON.stringify(e.currentTarget.dataset) + "------------传参")

    let TaskGuid = e.currentTarget.dataset.taskguid;
    let EquipmentName = e.currentTarget.dataset.equipmentname;
    let RecordBeginTime = e.currentTarget.dataset.recordbegintime;
    let TaskCompleteTime = e.currentTarget.dataset.taskcompletetime;
    let EquipmentLocation = e.currentTarget.dataset.equipmentlocation;

    wx.navigateTo({
      url: '../MaintainHistoryDetails/MaintainHistoryDetails?TaskGuid=' + TaskGuid + "&EquipmentName=" + EquipmentName + "&RecordBeginTime=" + RecordBeginTime + "&TaskCompleteTime=" + TaskCompleteTime + "&EquipmentLocation=" + EquipmentLocation
    })
  },

  switchNav(event) {
    var cur = event.currentTarget.dataset.current;
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 5;
    //tab选项居中                            
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth
    })
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
  },
  switchTab(event) {
    var cur = event.detail.current;
    var singleNavWidth = this.data.windowWidth / 5;
    this.setData({
      currentTab: cur,
      navScrollLeft: (cur - 2) * singleNavWidth
    });
    this.initData();
  },

  getSystemInfo: function() {
    var that = this
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  //获取设备详细信息
  initData: function() {
    var that = this
    var params = {
      TabNo: that.data.currentTab,
      EquipmentCode: that.data.EquipmentCode,
      RowGuid: that.data.RowGuid
    };
    httprequest.PostValidateRequest(httprequest.apiInfo.Project_GetEquipDetailMobileApi, params,
      function(res) {
        console.log(JSON.stringify(res) + "----------------------------接口返回参数详情")
        if (res.Data.IsSuccess == '0') {
          if (that.data.currentTab == '0') {
            console.log('IsAffiliate', res.Data.equipDatailData[0].IsAffiliate)
            if (res.Data.equipDatailData[0].IsAffiliate == 0) {
              that.setData({
                havefssb: true
              })
            } else {
              that.setData({
                havefssb: false
              })
            }
            if (res.Data.equipDatailData.length > 0) {
              console.log(dateutil.dateFormat3(res.Data.equipDatailData[0].InstallDate))
              var param = {
                EquipmentName: res.Data.equipDatailData[0].EquipmentName == null ? '' : res.Data.equipDatailData[0].EquipmentName,
                PropertyCode: res.Data.equipDatailData[0].PropertyCode == null ? '' : res.Data.equipDatailData[0].PropertyCode,
                EquipmentType: res.Data.equipDatailData[0].EquipmentType == null ? '' : res.Data.equipDatailData[0].EquipmentType,
                EquipmentSpecification: res.Data.equipDatailData[0].EquipmentSpecification == null ? '' : res.Data.equipDatailData[0].EquipmentSpecification,
                ManufactorName: res.Data.equipDatailData[0].ManufactorName == null ? '' : res.Data.equipDatailData[0].ManufactorName,
                Sys_TypeName: res.Data.equipDatailData[0].Sys_TypeName == null ? '' : res.Data.equipDatailData[0].Sys_TypeName,
                ClassifyName: res.Data.equipDatailData[0].ClassifyName == null ? '' : res.Data.equipDatailData[0].ClassifyName,
                SystemName: res.Data.equipDatailData[0].SystemName == null ? '' : res.Data.equipDatailData[0].SystemName,
                EquiptmentPosition: res.Data.equipDatailData[0].EquiptmentPosition == null ? '' : res.Data.equipDatailData[0].EquiptmentPosition,
                Supplier: res.Data.equipDatailData[0].Supplier == null ? '' : res.Data.equipDatailData[0].Supplier,
                Supplier_Tel: res.Data.equipDatailData[0].Supplier_Tel == null ? '' : res.Data.equipDatailData[0].Supplier_Tel,
                InstallDate: res.Data.equipDatailData[0].InstallDate == null ? '' : dateutil.dateFormat3(res.Data.equipDatailData[0].InstallDate)
              }
              console.log(param)
              var newarr = that.data.equipDatailData
              newarr.push(param)
              that.setData({
                equipDatailData: newarr,
                fssbCount: res.Data.equipAffiliateListCount,
                EquipmentName: res.Data.equipDatailData[0].EquipmentName,
                RowGuid: res.Data.equipDatailData[0].RowGuid,
                showzanwu: false
              })
              console.log(that.data.equipDatailData)
            } else {
              that.setData({
                showzanwu: true
              })
            }
          } else if (that.data.currentTab == '1') {
            if (res.Data.equipPropList.length > 0) {
              that.setData({
                jtsx_list: res.Data.equipPropList
              })
            } else {
              that.setData({
                showzanwu: true
              })
            }
          } else if (that.data.currentTab == '2') {
            if (res.Data.fileList.length > 0) {
              that.setData({
                fileList: res.Data.fileList,
                showzanwu: false
              })
            } else {
              that.setData({
                showzanwu: true
              })
            }
          } else if (that.data.currentTab == '3') {
            if (res.Data.equipInspectList.length > 0) {
              var RecordArray = that.data.RecordList;
              for (var i = 0; i < res.Data.equipInspectList.length; i++) {
                var params = {
                  RowGuid: res.Data.equipInspectList[i].RowGuid,
                  TaskName: res.Data.equipInspectList[i].TaskName,
                  Location: res.Data.equipInspectList[i].Location,
                  InspectDate: dateutil.dateFormat4(res.Data.equipInspectList[i].InspectDate),
                  IsAlarm: res.Data.equipInspectList[i].IsAlarm,
                  TaskRemark: res.Data.equipInspectList[i].TaskRemark,
                  EquipName: res.Data.equipInspectList[i].EquipName,
                }
                RecordArray.push(params)
              }
              that.setData({
                RecordList: res.Data.equipInspectList,
                showzanwu: false
              })
            } else {
              that.setData({
                showzanwu: true
              })
            }
          }else{
            if (res.Data.maintenancePlanList.length > 0) {
              that.setData({
                maintenancePlanList: res.Data.maintenancePlanList,
                showzanwu: false
              })
            } else {
              that.setData({
                showzanwu: true
              })
            }
          }
        } else {
          that.setData({
            showzanwu: true
          })
        }
      },
      function(err) {
        that.setData({
          showzanwu: true
        })
      })
  },

  //查看设备附件
  viewfile(e) {
    var that = this
    let filepath = e.currentTarget.dataset.filepath
    let filetype = e.currentTarget.dataset.filetype
    filetype = filetype.replace('.', '').toLowerCase()
    console.log('filetype', filetype)
    console.log('filepath', that.data.UploadUrl + filepath)

    //doc/docx/xls/xlsx/ppt/pptx/pdf
    if (filetype.indexOf('doc') != -1 || filetype.indexOf('xls') != -1 || filetype.indexOf('ppt') != -1 || filetype.indexOf('pdf') != -1) {
      console.log('打开的是文档')
      wx.showLoading({
        title: '加载中...',
      })
      wx.downloadFile({
        url: that.data.UploadUrl + filepath,
        success: function(res) {
          console.log(res)
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType: filetype,
            success: function(res) {
              console.log('打开文档成功')
              wx.hideLoading()
            },
            fail: function(err) {
              console.error('打开文档失败', err)
              wx.hideLoading();
              that.setData({
                info: '文件较大建议使用PC端查看'
              })
            }
          })
        },
        fail: function(err) {
          console.error(err)
          wx.hideLoading()
          that.setData({
            info: '文件较大建议使用PC端查看'
          })
        }
      })
    } else if (filetype.indexOf('jpg') != -1 || filetype.indexOf('jpeg') != -1 || filetype.indexOf('png') != -1 ||
      filetype.indexOf('bmp') != -1 || filetype.indexOf('gif') != -1) {
      wx.showLoading({
        title: '加载中...',
      })
      console.log('打开的是图片')
      wx.previewImage({
        current: that.data.UploadUrl + filepath, // 当前显示图片的http链接
        urls: [that.data.UploadUrl + filepath] // 需要预览的图片http链接列表
      })
      wx.hideLoading();
    } else if (filetype.indexOf('mp4') != -1 || filetype.indexOf('avi') != -1 || filetype.indexOf('mov') != -1 ||
      filetype.indexOf('flv') != -1 || filetype.indexOf('m4v') != -1) {
      if (that.data.platform == 'android' && (filetype.indexOf('avi') != -1 || filetype.indexOf('mov') != -1 || filetype.indexOf('m4v') != -1)) {
        that.setData({
          info: '安卓暂不支持查看该类型文件'
        })
        return
      }
      console.log('打开的是视频')
      console.log(this.data.platform)
      wx.showLoading({
        title: '加载中...',
      })
      that.setData({
        dialogShow: true,
        videourl: that.data.UploadUrl + filepath
      })
      wx.hideLoading();
    } else {
      that.setData({
        info: '暂不支持查看该类型文件'
      })
    }
  },

  videoerror(e) {
    console.error(e.detail.errMsg);
  },

  makephonecall: function(e) {
    if (e.currentTarget.dataset.phone != null && e.currentTarget.dataset.phone != '') {
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.phone,
      })
    } else {
      this.setData({
        info: '暂无供应商电话'
      })
    }
  },

  //跳转附属设备
  navfssb: function(e) {
    console.log('跳转附属设备', e)
    if (this.data.fssbCount == 0) {
      this.setData({
        info: '暂无附属设备'
      })
    } else {
      wx.navigateTo({
        // url: '/pages/equip_detail/equip_detail?RowGuid=' + e.currentTarget.dataset.rowguid + '&EquipmentCode=' + e.currentTarget.dataset.equipmentcode + '&EquipmentName=' + e.currentTarget.dataset.equipmentname
        url: '/pages/equipment/equipment?ParentGuid=' + e.currentTarget.dataset.rowguid + '&EquipmentName=' + e.currentTarget.dataset.equipmentname + '&havefssb=1'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('onLoad', options)

    this.setData({
      CustomBar: (app.globalData.titleBarHeight + app.globalData.statusBarHeight) * 2
    })

    // if (options.RowGuid != undefined && options.EquipmentCode != undefined && options.EquipmentName != undefined &&
    //   options.EquipmentCode != '' && options.RowGuid != '' && options.EquipmentName != '') {
    if (options.EquipmentCode != undefined && options.EquipmentCode != '') {
      this.setData({
        RowGuid: options.RowGuid,
        EquipmentCode: options.EquipmentCode,
        // title: options.EquipmentName + '设备详情',
        // EquipmentName: options.EquipmentName
      })
      if (options.havefssb != undefined && options.havefssb == '1') {
        this.setData({
          havefssb: false
        })
      }
      this.initData();
    }
    this.getSystemInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})